<?php


namespace app\common\cachemodel;

use app\common\model\BaseCache;
use Exception;
use think\Log;
use XznsTools\cache\CacheManage;

class MentalUserRecordModel extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.mt_user_record';
    protected $cacheModel = 'mental_test.record';
    protected $cacheModelRecent = 'mental_test.recent';
    protected $cacheModelAnswer = 'mental_test.answer';

    private $LOG_PRE = '测评记录Model：';

    private $LIST_KEYS = ['id', 'create_time', 'uid', 'qid', 'status', 'order_id', 'result_url', 'name', 'picture', 'child_id', 'account_id'];

    /**
     * 查询用户的最近一次的测评记录
     * @param $uid
     * @param $qid
     * @param int $child_id
     * @return array|bool|mixed|string
     * @throws Exception
     */
    public function getUserRecentRecord($uid, $qid, $child_id = 0)
    {
        return CacheManage::getInstance()->setCacheConfig($this->cacheModelRecent, $uid . ':' . $qid . ':' . $child_id)
            ->getDataAndSet(function () use ($uid, $qid, $child_id)
            {
                try
                {
                    $where = [];
                    if ($uid)
                    {
                        $where['uid'] = $uid;
                    }
                    if ($qid)
                    {
                        $where['qid'] = $qid;
                    }
                    if ($child_id)
                    {
                        $where['child_id'] = $child_id;
                    }

                    $data = $this
                        ->where($where)
                        ->field('id,status,child_id,order_id,create_time,qid')
                        ->order('create_time', 'desc')
                        ->findOrFail()->toArray();
                }
                catch (Exception $e)
                {
                    $data = [];
                }

                return $data;
            });
    }

    /**
     * 获取用户的答题记录
     * @param $uid
     * @param string $order_id
     * @return array|bool|mixed|string
     * @throws Exception
     */
    public function getUserRecrodDetail($uid, $order_id = '')
    {
        return CacheManage::getInstance()->setCacheConfig($this->cacheModelAnswer, $uid . ':' . $order_id)
            ->getDataAndSet(function () use ($uid, $order_id)
            {
                try
                {
                    $where = [];
                    if ($uid)
                    {
                        $where['uid'] = $uid;
                    }

                    if ($order_id)
                    {
                        $where['order_id'] = $order_id;
                    }

                    $data = $this
                        ->where($where)
                        ->field('id,status,answer_content,child_id,order_id,create_time,qid,account_id,result_url')
                        ->order('create_time', 'desc')
                        ->findOrFail()->toArray();
                }
                catch (Exception $e)
                {
                    $data = [];
                }

                return $data;
            });
    }

    /**
     * 新增测评记录
     * @param array $data
     * @return int
     */
    public function saveData(array $data): int
    {
        try
        {
            // 新增
            $record_id = $this->insertGetId($data);
            // 列表新增数据
            $this->listDataAdd($data['uid'], [$record_id => $record_id], $data['status'] ?? 1);
            // 更新用户的答题记录
            CacheManage::getInstance()->setCacheConfig($this->cacheModelAnswer, $data['uid'] . ':' . $data['order_id'])->setCache($data);
            // 删除用户最近的答题记录
            CacheManage::getInstance()->setCacheConfig($this->cacheModelRecent, $data['uid'] . ':' . $data['qid'] . ':' . $data['child_id'])->rmCache();
            return true;
        }
        catch (Exception $e)
        {
            Log::write($this->LOG_PRE . $e->getMessage() . "；错误文件「{$e->getFile()}」错误行数「{$e->getLine()}」", 'error', true);
            return false;
        }
    }


    /**
     * 更新结果数据
     * @param $data
     * @return bool
     */
    public function updateData($data): ?bool
    {
        try
        {
//            $child_id = $data['child_id'] ?? '';
//            $order_id = $data['order_id'] ?? '';
            // 更新
            $id = $data['id'];
            unset($data['id']);
            $this->where('id', $id)->update($data);
            if (isset($data['status']))
            {//操作我的测评列表缓存
                if (1 === $data['status'])
                {
                    $this->listDataDel($data['uid'], [$id => $id], 2);
                    $this->listDataAdd($data['uid'], [$id => $id], 1);
                    // 更新用户最近的答题记录
                    CacheManage::getInstance()->setCacheConfig($this->cacheModelRecent, $data['uid'] . ':' . $data['qid'] . ':' . $data['child_id'])->setCache($data);
                } else
                {
                    $this->listDataDel($data['uid'], [$id => $id], 1);
                    $this->listDataAdd($data['uid'], [$id => $id], 2);
                    // 删除用户最近的答题记录
                    CacheManage::getInstance()->setCacheConfig($this->cacheModelRecent, $data['uid'] . ':' . $data['qid'] . ':' . $data['child_id'])->rmCache();
                }
                //更新记录详情缓存
                CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->setCache($data);
                // 更新的答题记录
                CacheManage::getInstance()->setCacheConfig($this->cacheModelAnswer, $data['uid'] . ':' . $data['order_id'])->setCache($data);
            }

            return true;
        }
        catch (Exception $e)
        {
            Log::write($this->LOG_PRE . $e->getMessage() . "；错误文件「{$e->getFile()}」错误行数「{$e->getLine()}」", 'error', true);
            return false;
        }
    }


    /**
     * 获取用户答题记录
     * @param int $uid 用户id
     * @param int $status 答题状态 1=> 未完成，2=> 已完成
     * @return array|mixed
     * @throws Exception
     */
    public function getRecordList($uid = 0, $status = 1)
    {
        return $this->getListPage($uid, 'id', $this->LIST_KEYS, $status, 'desc', 0, 'list');
    }

    /**
     * 批量获取数据
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|false|string|void
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        $uid = $type[0];
        if (isset($type))
        {
            $status = $type[1];
        }

        $where = [];
        if ($ids)
        {
            $where = ['r.id' => ['in', $ids]];
        } else
            if (isset($status))
            {
                $where = ['r.uid' => $uid, 'r.status' => $status];
            }
        try
        {
            $data = $this->where($where)
                ->alias('r')
                ->join('wechat_backup_07_18_14_43_00.mt_questions q', 'q.id=r.qid or (q.parent_id=r.qid and q.oid=r.child_id)')
                ->order('r.create_time', 'desc')
                ->column('r.id,r.create_time,r.uid,r.qid,r.status,order_id,r.child_id,q.picture,q.name', 'r.id');

            foreach ($data as $k => $v)
            {
                //处理时间显示
                if (isset($v['create_time']))
                {
                    $v['create_time'] = date('Y年m月d日', $v['create_time']);
                }
                $data[$k] = $v;
            }
        }
        catch (Exception $e)
        {
            $data = [];
            Log::write($this->LOG_PRE . '获取详情异常：' . $e->getMessage(), 'error', true);
        }
        return $data;
    }
}
